<template>
  <div class="book" v-cloak>
    <mt-header fixed :title="book.title">
      <mt-button  slot="left" icon="back" @click="$router.push('/novels')">返回</mt-button>
    </mt-header>

      <mt-cell
        v-for="item in chapters"
        :to="item.read"
        :title="item.name"
        :key="item.name"
        is-link
      >
      </mt-cell>
    <div class="page-box" v-show="totalPage>1">
      <mt-button @click="prevPage" v-show="page>1">←</mt-button>
      第
      <input type="number" v-model="page" class="page">/{{totalPage}}页
      <mt-button @click="toPage">Go</mt-button>
      <mt-button @click="nextPage" v-show="page<totalPage">→</mt-button>
    </div>

  </div>
</template>
<script>
  import fetch from '../utils/fetch'
  import { mapGetters } from 'vuex';
  export default {
    data(){
      return {book:{},chapters:[],page:1,loading:true,totalPage:0}
    },
    methods:{
      getBook(){
        fetch(`${this.url}novels/${this.$route.params.novelId}`).then(res=>{
          this.book = res.data;
          this.totalPage = res.data.totalPage;
          this.chapters.push(...this.book.chapters)
        })
      },
      nextPage(){
        this.page ++ ;
        this.toPage();
      },
      prevPage(){
        this.page -- ;
        this.toPage();
      },
      toPage(){
        if(this.page>this.totalPage){
          this.page = this.totalPage
        }
        if(this.page>0&&this.page<=this.totalPage){
          fetch(`${this.url}novels/${this.$route.params.novelId}?page=${this.page}`).then(res=>{
            this.book = res.data;
            this.chapters=this.book.chapters;
            window.scrollTo(0,0)
          })
        }
      }
    },
    computed: {
      ...mapGetters([
        'url'
      ])
    },
    created(){
      let index = location.host.indexOf('gakki')>=0?1:0;
      this.$store.dispatch('switchUrl',index);
      this.getBook();
      document.body.onkeydown=(e) => {
        if(e.keyCode==37){
          this.prevPage();
        }
        if(e.keyCode==39){
          this.nextPage();
        }
      }
    }
  }
</script>
<style scoped>
  .page{
    width: 3em;
    height: 1.5em;
    border-radius: 5px;
    border: thin solid #cccccc;
    margin: 0 0.5em;
    outline: none;
    text-align: center;
  }
  .page-box{
    padding: 10px;
    text-align: center;

  }
  .book{
    text-align: left;
    padding-top: 40px;
  }
</style>
